﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.IService;
using ZSZ.Model;

namespace ZSZ.Service
{
    public partial class HouseAttachmentService : BaseService<HouseAttachment>, IHouseAttachmentService
    {
        public void Add(long houseId, long[] attachmentIds)
        {
            //房源是否存在
            House house = DbSession.HouseDal.GetById(houseId);
            if (house == null)
            {
                throw new ArgumentException("房源不存在" + houseId);
            }

            if (attachmentIds == null)
            {
                throw new ArgumentException("未设置房源" + attachmentIds + "配套设施");
            }

            //配套设施是否存在
            var attachments = DbSession.AttachmentDal.GetAll().Where(a => attachmentIds.Contains(a.Id)).ToArray();
            foreach (var attachment in attachments)
            {
                HouseAttachment ha = new HouseAttachment();
                ha.HouseId = houseId;
                ha.AttachmentId = attachment.Id;
                ha.IsDeleted = false;
                ha.CreateDateTime = DateTime.Now;
                CurrentDal.Add(ha);
            }
            DbSession.SaveChanges();
        }

        public void Update(long houseId, long[] attachmentIds)
        {
            //房源是否存在
            House house = DbSession.HouseDal.GetById(houseId);
            if (house == null)
            {
                throw new ArgumentException("房源不存在" + houseId);
            }

            if (attachmentIds == null)
            {
                throw new ArgumentException("未设置房源" + attachmentIds + "配套设施");
            }

            //删除旧数据
            //house.HouseAttachments.Clear();
            var houseAttachments = CurrentDal.GetAll().Where(ha => ha.HouseId == houseId);
            foreach (var ha in houseAttachments)
            {
                BatchDeleted(ha);
            }

            //配套设施是否存在
            var attachments = DbSession.AttachmentDal.GetAll().Where(p => attachmentIds.Contains(p.Id)).ToArray();
            foreach (var attachment in attachments)
            {
                HouseAttachment ha = new HouseAttachment();
                ha.HouseId = houseId;
                ha.AttachmentId = attachment.Id;
                ha.IsDeleted = false;
                ha.CreateDateTime = DateTime.Now;
                CurrentDal.Add(ha);
            }
            DbSession.SaveChanges();
        }
    }
}
